/**
 * 
 */
package com.cn.practice.flyweight;

import java.util.HashMap;

/**
 * 享元模式练习
 * @author zhangyang
 *
 */
public class FlyWeightPractice {
public static void main(String[] args) {
	//使用享元工厂构建享元对象
	ConcretFlyWeightFacory facory = new ConcretFlyWeightFacory();
	SoftWare softWare1 = facory.getFlyWeight("报纸");
	//让tom使用享元对象
	softWare1.use(new User("tom"));
	SoftWare softWare2 = facory.getFlyWeight("新闻");
	softWare2.use(new User("catty"));
	SoftWare softWare3 = facory.getFlyWeight("报纸");
	softWare3.use(new User("green"));
	//查看享元对象池的对象个数
	System.out.println(facory.getFlyWeightSize());
	
}
}

/**
 * 抽象对象 软件
 * @author zhangyang
 *
 */
abstract class SoftWare{
	/**
	 * 定义方法 使用 里面包含一个内部状态User
	 * @param user
	 */
	 public abstract void use(User user);
}

/**
 * 内部状态-不会构建到享元工厂
 * @author zhangyang
 *
 */
class User{
	String name;

	
	public User(String name) {
		super();
		this.name = name;
	}


	@Override
	public String toString() {
		return "User [name=" + name + "]";
	}
	
}

/**
 * 具体享元对象
 * @author zhangyang
 *
 */
class ConcretSoftWare extends SoftWare{

	/**
	 * 外部状态
	 */
	String type;
	
	public ConcretSoftWare(String type) {
		super();
		this.type = type;
	}

	@Override
	public void use(User user) {
		// TODO Auto-generated method stub
		System.out.println("享元模式构建出来的发布对象-类型是"+type+"用户是"+user);
	}
	
}

/**
 * 享元工厂
 * @author zhangyang
 *
 */
class ConcretFlyWeightFacory{
	
	HashMap<String,ConcretSoftWare> resources=new HashMap<>();
	
	public SoftWare getFlyWeight(String type) {
		if(!resources.containsKey(type)) {
			resources.put(type, new ConcretSoftWare(type));
		}
		
		return resources.get(type);
	}
	
	public int getFlyWeightSize() {
		return resources.size();
	}
}